package com.cqs.learning.spring.cloud.producer.task;

import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 不断产生消息
 *
 * @author lixw
 * @date 2020/3/24 23:46
 */
@Component
@Log4j2
public class MsgProducerWorker implements Runnable {


    @Resource(name = "redisTemplate")
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private TaskExecutor taskExecutor;

    @Override
    public void run() {
        while (true) {
            String msg = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
            String key = String.valueOf(System.currentTimeMillis());
            redisTemplate.boundValueOps(key).set(msg);
            redisTemplate.boundValueOps(key).expire(1, TimeUnit.DAYS);
            log.info("生成消息: " + msg);
            try {
                TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000) * 5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @PostConstruct
    public void runTask() {
//        run();
//        taskExecutor.execute(this::run);
    }

    public static void main(String[] args) {
        String msg = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
        System.out.println(msg);
    }
}
